package com.xysoft.admin;

import java.util.Date;
import java.util.HashMap;

import com.xysoft.ServiceLocator;
import com.xysoft.admin.common.SessionInfo;
import com.xysoft.admin.dao.IBaseDao;
import com.xysoft.model.User;

public class SessionContext {
	private static SessionContext instance;
	private static IBaseDao baseDao;
    private HashMap<String, SessionInfo> mymap;
    private SessionContext() {
        mymap = new HashMap<String, SessionInfo>();
    }
    public static SessionContext getInstance() {
        if (instance == null) {
            instance = new SessionContext();
        }
        return instance;
    }
    
    private static IBaseDao getBaseDao() {
    	if (baseDao == null) {
    		baseDao = ServiceLocator.getService(IBaseDao.class);
    	}
    	return baseDao;
    }
    
    public synchronized void AddSession(SessionInfo session) {
        if (session != null) {
            mymap.put(session.getId(), session);
        }
    }
    
    public synchronized void DelSession(String session_id) {
    	if (mymap.containsKey(session_id)) {
    		SessionInfo session = mymap.get(session_id);
    		User user = (User)getBaseDao().get(User.class, session.getUser().getId());
    		user.setLastTime(new Date());
    		getBaseDao().save(user);
    		mymap.remove(session_id);
    	}
    }
    
    public synchronized SessionInfo getSession(String session_id) {
        if (session_id == null) return null;
        return (SessionInfo) mymap.get(session_id);
    }
}
